<template>
    <view class="content">
        <van-popup position="bottom" @click-overlay="closeCurrentPopup" :show="show" round z-index=104
            custom-style="width: 100%;background:#ffffff;overflow: hidden;height:90% ">
            <view class="popup-content">
                <!-- <scroll-view :refresher-enabled="false" class="scroll-content" scroll-y :lower-threshold="80" show-scrollbar="false"> -->

                <view class="popup-main">
                    <view style="display: flex; justify-content: space-between;">
                        <view class="popupTitle"> {{title}}</view>
                        <view>
                            <van-icon name="cross" size="15" @click="closeCurrentPopup" />
                        </view>
                    </view>
                    <view class="comment-item">
                        <view>
                            <view class="user-info user-info-main">
                                <view class="user-info-left" style="display: flex; align-items: center;">
                                    <img :src="comments.wxUserInfo.avatarUrl ? comments.wxUserInfo.avatarUrl : defaultAvatarUrl"
                                        alt="">
                                    <view class="user-name" >{{ comments.wxUserInfo.nickName }}</view>
                                </view>
                                <template v-if="pageSymbol !== 'myActCommentDetails'">
                                    <van-button size="mini" class="guanzhu" type="default">{{
                                        comments.currentUserFollow == true ? '已关注' : '关注' }}</van-button>
                                </template>
                            </view>
                            <view class="comment-content">{{ comments.content }}</view>
                        </view>
                        <template v-if="level == 1">
                            <view class="image-container" v-if="comments.attachment && comments.judgeImages.length > 0">
                                <view class="imgInfo" v-for="(i, j) in comments.judgeImages.slice(0, 3)" :key="j">
                                    <img :src="i" />
                                </view>
                            </view>
                        </template>
                        <view class="comment-footer">
                            <view class="time">{{localComments.formattedPublishTime}}</view>
                            <!-- 点赞数在底部 -->
                            <view class="interaction" v-if="pageSymbol == 'myActCommentDetails'">
                                <!-- <van-icon name="chat-o" style="margin-right: 8rpx;" size="12" />
                                <view class="count" style="margin-right:40rpx;">{{ comments.commentCount }}
                                </view>
                                <view @click.stop="handlerLikeItem(item)" style="padding-right: 8rpx;">
                                    <van-icon name="good-job-o" size="15" style="color:#888888 !important;"
                                        v-if="!item.currentUserLike" />
                                    <van-icon name="good-job" size="15" style="color:#FF6203 !important;"
                                        v-if="item.currentUserLike" />
                                </view>
                                <view class="count">{{ item.likeCount }}</view> -->
                            </view>
                        </view>
                    </view>
                    <scroll-view class="scroll-content " scroll-y :lower-threshold="120" show-scrollbar="false">
                        <view class="commentPopup-wrapper ">
                            <view class="newReply" v-if="secondCommentList.length>0">
                                <view class="replyTitle">全部回复</view>
                                <view class="replyList">
                                    <view class="reply-item" v-for="(item, index) in secondCommentList" :key="index">
                                        <view class="userInfo_avatar" @tap="toSendThirdReply(item)"> <img
                                                :src="item.wxUserInfo.avatarUrl? item.wxUserInfo.avatarUrl : defaultAvatarUrl"
                                                alt=""> </view>
                                        <view class="reply-item_left">
                                            <view class="user-info reply-user-info" @tap="toSendThirdReply(item)">
                                                <view class="user-info-left" style="display: flex; align-items: center;">
                                                    <view class="user-name">{{ item.wxUserInfo.nickName }}</view>
                                                </view>
                                                <view class="replyTime">{{item.formattedTime}}·回复</view>
                                            </view>
                                            <view class="_parentReplyInfo" v-if="item.parent" @tap="toShowThirdReply(item)">
                                                <span class="_parentNickName">@{{item.parent.wxUserInfo.nickName }}</span> <span class="_parentContent">: {{item.parent.content}}</span>
                                            </view>
                                            <view class="reply-content comment-content" @tap="toSendThirdReply(item)">{{ item.content }}
                                            </view>
                                            <view class="comment-footer">
                                                <view class="time"> </view>
                                                <view class="interaction">
                                                    <view @click.stop="handlerReplyLike(item)" style="margin-right: 8rpx;">
                                                        <van-icon name="good-job-o" size="15"
                                                            style="color:#888888 !important;" v-if="!item.ifLike" />
                                                        <van-icon name="good-job" size="15"
                                                            style="color:#FF6203 !important;" v-if="item.ifLike" />
                                                    </view>
                                                    <view class="currentNum" v-if="item.likeCount >0">{{ item.likeCount }}</view>
                                                </view>
                                            </view>
                                            <!-- <view class="reply_comment_num">
                                                {{item.commentCount}}回复 <van-icon name="arrow" size="12"
                                                    style="margin-left: 24rpx;" />
                                            </view> -->
                                        </view>
                                    </view>
                                    <view v-if="loading" class="loading-text">正在加载...</view>
                                    <view v-if="finished" class="no-more-text">没有更多了</view>
                                </view>
                                <view class="replyList" v-if="secondCommentList.length==0">
                                    <view class="noReply">当前暂无回复</view>
                                </view>
                            </view>
                            <!-- <view class="reply_tips" v-if="comments.commentCount > 0">  抢先回复 </view>
                            <view class="input-section">
                                <view class="my-reply-input">
                                    <input :placeholder="`回复 ${comments.wxUserInfo.nickName || '用户'}：`" :value="myReplyContent" @input="inputMyReply" confirm-type="send" 	adjust-position="true" type="text" maxlength="200"	 @confirm="handleSendReply" />
                                </view>
                                <button class="send-btn" @tap="handleSend"  :disabled="isSubmitting"
                                :class="{ 'disabled-btn': isSubmitting }">发布</button>
                            </view> -->
                        </view>
                    </scroll-view>
                    <view class="replyFooter">
                        <view class="replyInput" @tap="handlerSendSecondReply(2)">我也来说~</view>
                        <!-- 主评论的点赞与评论数 -->
                        <view class="reply-interaction">
                            <view
                                style="margin-right: 40rpx;display: flex; flex-direction: column; justify-content: center;">
                                <van-icon name="chat-o" />
                                <view class="currentNum">{{ comments.commentCount }}</view>
                            </view>
                            <view @click.stop="handlerLike(comments)"
                                style="display: flex; flex-direction: column; justify-content: center;">
                                <van-icon name="good-job-o" size="15" style="color:#888888 !important;"
                                    v-if="!comments.ifLike" />
                                <van-icon name="good-job" size="15" style="color:#FF6203 !important;"
                                    v-if="comments.ifLike" />
                                <view class="currentNum">{{ comments.likeCount }}</view>
                            </view>

                        </view>
                    </view>

                    <van-toast id="van-toast" />
                </view>
            </view>
            <send-first-reply :show="showSendReply" :pageSymbol="pageSymbol" :comments="commentsData" :defaultAvatarUrl="defaultAvatarUrl"
            :activityId="activityId" :postId="nowReplyId" @closePopup="closePopup"
            @reply-success="handleReplySuccess" :level="currentLevel"></send-first-reply>
             <thirdLevelReply :show="showThirdReply" @closeThirdReplyPopup="closeThirdReplyPopup" :commentId="handleCommentId" :activityId="activityId" ></thirdLevelReply>
        </van-popup>
    </view>
</template>

<script>
import Toast from '@/wxcomponents/vant/toast/toast'
import {addCommentApi} from '@/api/activity'
import {getSecondCommentListApi,getThirdCommentListApi } from '@/api/activity'
import { likeCommentApi } from '@/api/judge' // 导入点赞接口
import sendFirstReply from '@/mycomponents/activity/sendFirstReply.vue'
import  thirdLevelReply from '@/mycomponents/activity/thirdLevelReply.vue'
import { formatRelativeTime } from '@/utils/time-format-utility';


export default {
    components: {
        sendFirstReply,
        thirdLevelReply
    },
    props: {
        show: {
            type: Boolean,
            default: () => false
        },
        comments:{
            type:Object,
            default:()=>{}
        },
        pageSymbol:{
            type:String,
            default:''
        },
        defaultAvatarUrl: {
            type: String,
            default: ''
        },
        activityId:{
            type:String,
            default:''
        },
        postId:{ //一级评论用这个
            type:String,
            default:''
        },
        level:{
            type:Number,
            default:0
        }
    },
    data () {
        return {
            curS:0,
            curSName:'',
            date: '',
            title: '暂无回复',
            popupHeight: '80%',
            myReplyContent:undefined,
            isSending: false,
            parentId:undefined, // 父评论的 ID
            secondCommentList:[],
            thirdCommentList:[],
            pageNum:1,
            pageSize:10,
            total:0,
            loading: false,
            finished: false,
            hasData:false,  //是否有数据
            showSendReply:false,
            commentsData:{},
            pageSizeThird:10,
            pageNumThird:1,
            totalThird:0,
            loadingThird:false,
            finishedThird: false,
            nowReplyId:undefined,
            currentLevel:2,
            showThirdReply:false, //显示三级
            handleCommentId:undefined, //显示三级评论 需要的id
            localComments:{},//主评论时间
        }
    },

    computed: {
    },


    watch: {
        show: {
            immediate: true, // 这句重要
            handler(v) {
                console.log(v, 'v',this.comments,'this.comments')
                if (v) {
                    this.getSecondCommentList()
                    const commentCount = this.comments?.commentCount || 0;
                    this.title = commentCount > 0 ? `${commentCount}条回复` : '暂无回复';
                }
            },
            deep: true
        },
        comments: {
            immediate: true, // 这句重要
            handler(v) {
                console.log(v, 'v',)
                if (v) {
                    const processedComments = { ...v };
                    // 处理发布时间
                    if (processedComments.publishTime) {
                        processedComments.formattedPublishTime = this.formatTime(processedComments.publishTime);
                    }
                    this.localComments = processedComments;
                }
            },
        }
        // show (newVal) {
        //     if (newVal) {
        //         console.log(newVal,this.comments,'this.comments')
        //         const commentCount = this.comments?.commentCount || 0;
        //         this.title = commentCount > 0 ? `${commentCount}条回复` : '暂无回复';
        //     }
        // }
    },
    onLoad () {

    },
    onReady () {
    },

    methods: {   
        formatTime(timestamp) {
            return formatRelativeTime(timestamp);
        },    
        // 关闭弹窗
        closeCurrentPopup () {
            this.$emit('closePopup')
        },

        handlerSendSecondReply(val){
            this.currentLevel = val
            this.nowReplyId = this.comments.id
            this.commentsData = this.comments
            this.showSendReply=true
            console.log(this.nowReplyId,'this.nowReplyId')
        },
        // 发布三级评论
        toSendThirdReply(item){
            console.log(item,'item')
            this.nowReplyId = item.id
            this.currentLevel = 3 //当前是1级别评论 发布的是二级评论
            this.commentsData = item
            this.showSendReply=true
        },

        closePopup(){
            this.showSendReply=false
            // this.showSecondReply = false
        },
        // 发布首评、新增回复成功处理
        handleReplySuccess() {
            // this.closePopup()
            this.clearData()
            this.getSecondCommentList() // 刷新评论数据
        },
        // 去三级评论
        toShowThirdReply(item){
            this.handleCommentId = item.id
            this.showThirdReply = true
        },
        closeThirdReplyPopup(){
            this.showThirdReply = false
        },

         // 主评论点赞
         handlerLike() {
            this.comments.ifLike = !this.comments.ifLike
            if (this.comments.ifLike) {
                this.comments.likeCount++
            } else {
                this.comments.likeCount--
            }
            this.likeComment(this.comments.id)
        },

        // 二级评论点赞
        handlerLikeItem(item){
            item.ifLike = !item.ifLike
            this.likeComment(item.id)
        },

        // 二级回复点赞
        handlerReplyLike(item){
            item.ifLike =!item.ifLike
            if (item.ifLike) {
                item.likeCount ++
            }else{
                item.likeCount --
            }
            this.likeComment(item.id)
        },
        // 调用一级评论 清空数据  
        clearData(){
            this.secondCommentList=[]
            this.pageNum=1
            this.pageSize =10
            this.total=0
            this.finished=false
            this.hasData=false
        },
        clearDataThird(){
            this.thirdCommentList=[]
            this.pageNumThird=1
            this.pageSizeThird =10
            this.totalThird=0
            this.finishedThird=false
            // this.hasData=false
        },
        // 二级评论
        getSecondCommentList() {
            if (this.loading || this.finished) return;
            this.loading = true;
            
            return new Promise((resolve, reject) => {
                getSecondCommentListApi({
                    commentId: this.postId,
                    pageSize: this.pageSize,
                    pageNum: this.pageNum,
                    activityId: this.activityId,
                }).then(res => {
                    console.log(res, 'getSecondCommentListApi')
                    if (res.code === 200) {
                        this.total = res.data.total;
                        // 修改数据合并方式
                        // this.secondCommentList = this.pageNum === 1
                        //     ? res.data.list
                        //     : [...this.secondCommentList, ...res.data.list];
                        // 新增时间格式化处理
                        const processedList = res.data.list.map(item => ({
                            ...item,
                            formattedTime: this.formatTime(item.publishTime)
                        }));

                        this.secondCommentList = this.pageNum === 1
                            ? processedList  // 使用处理后的数据
                            : [...this.secondCommentList, ...processedList];


                        this.finished = this.secondCommentList.length >= this.total;
                        this.pageNum++;
                        console.log(this.secondCommentList, 'this.secondCommentList')
                        this.hasData = this.secondCommentList.length > 0
                        resolve(res)
                    } else {
                        reject(res)
                    }
                }).finally(() => {
                    this.loading = false;
                })
            })
        }, 
        // 点赞  取消点赞
        likeComment(replyId){
            return new Promise((resolve, reject) => {
                const params={
                    commentId:replyId,
                    interactionsTargetType:'comment'
                }
                likeCommentApi(params).then((res) => {
                    console.log(res)
                    if (res.code === 200) {
                        console.log('res-----', res.data)
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        },

  },

}
</script>
<style lang="scss" scoped>


::v-deep .van-button__text {
    // display: inline-block;
    display: flex !important;
    flex-direction: column !important;
}
// 滚动
.scroll-content {
    flex: 1;
    height: 1px;
}

// 提示框
.popup-content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 24px;
    border-radius: 16px;
    overflow: hidden;
    // height:100vh;
    height: 100%;


    .popup-main {
        height: 100%;
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
    }


    .popupTitle {
        font-size: 20px;
        text-align: left;
        color: #111111;
        line-height: 20px;
    }


    // 综合评论 公用
    .comment-item {
        padding-top: 46rpx;
        background-color: white;
        border-radius: 8rpx;
        overflow: hidden;
        border-bottom: 1rpx solid #efefef;
    }

    .reply-item {
        display: flex;
        margin-bottom: 64rpx;
    }

    .userInfo_avatar {
        img {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            margin-right: 24rpx;
        }
    }

    .user-info-main{
        justify-content: space-between;
    }
    .user-info {
        display: flex;
        align-items: center;

        .user-info-left {
            display: flex;
            align-items: center;
            // margin-right: 48rpx;

            img {
                width: 80rpx;
                height: 80rpx;
                border-radius: 50%;
                margin-right: 24rpx;
            }
        }
    }

    .user-name {
        font-size: 28rpx;
        text-align: left;
        color: #333;
        // max-width: 146rpx;
        // white-space: nowrap;
        // /* 防止文本换行 */
        // overflow: hidden;
        // /* 超出部分隐藏 */
        // text-overflow: ellipsis;
        // /* 显示省略号 */
    }
    .replyTime{
        font-weight: 400;
        font-size: 24rpx;
        text-align: left;
        color: #999;
        margin-left: 48rpx;
    }

    // 评论内容
    .comment-content {
        margin-top: 24rpx;
        font-weight: 400;
        font-size: 32rpx;
        line-height: 48rpx;
        text-align: left;
        color: #333;
    }

    ._parentReplyInfo{
        margin-top: 24rpx;
        border-radius: 12rpx;
        background: #f9f9f9;
        padding: 28rpx 24rpx;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: normal;

        ._parentNickName{
            color: #333333;
            font-size: 28rpx;
            font-weight: 400;
            letter-spacing: 0;
        }
       ._parentContent{
            color: #999999;
            font-size: 28rpx;
            font-weight: 400;
            letter-spacing: 0;
        }
    }
    .image-container {
        display: flex;
        flex-wrap: wrap;
        // height: 330rpx;
        width: 100%;

        // gap: 5rpx; /* 新增间距 */
        .imgInfo {
            width: calc((100% - 10rpx)/3);
            /* 调整宽度适配间隙 */
            overflow: hidden;
            /* 防止图片溢出 */
            margin-bottom: 10rpx;
        }

        img {
            height: 220rpx;
            width: 100%;
        }

        .imgInfo:nth-child(2n) {
            margin-bottom: 0rpx;
            /* 调整下间距 */
        }
    }

    .comment-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10rpx 10rpx 40rpx 10rpx;
        font-size: 24rpx;
        color: #999;
    }

    .comment-footer .time {
        font-weight: 400;
        font-size: 24rpx;
        text-align: left;
        color: #999;
    }

    .reply_tips{
        padding-top: 24rpx;
        font-weight: 400;
        font-size: 24rpx;
        text-align: center;
        color: #999;
    }
    .input-section {
        display: flex;
        align-items: flex-end; /* 使子元素在交叉轴上底部对齐 */
        margin-top: 60rpx;
    }
    .my-reply-input{
        min-height: 144rpx;
        border-radius: 8rpx;
        background: #f4f4f4;
        padding: 24rpx;
        width: 78%;
    }
    .send-btn {
        margin-left: 16rpx;
        padding: 0 16rpx;
        height: 40rpx;
        line-height: 40rpx;
        background-color: #ff6203;
        color: white;
        border: none;
        border-radius: 50rpx;
        font-size: 20rpx;
    }
}
// 最新评论、回复
.newReply{
   margin-top: 40rpx;
    .replyList{
        margin-top: 40rpx;
    }
    // 点赞
    .interaction{
        display: flex;
        align-items: center;
    }

}
.reply-item_left{
    width: calc(100% - 104rpx);

    .reply-user-info{
        width: 100%;
        height: 80rpx;
        line-height: 80rpx;
    }
    // .reply-content{
    //     margin-top: 24rpx;
    //     font-weight: 400;
    //     font-size: 32rpx;
    //     line-height: 48rpx;
    //     text-align: left;
    //     color: #333;
    // }
}

// 底部回复
.replyFooter{
    position: fixed;
    display: flex;
    align-items: center;
    justify-content: space-between;
    // padding:12rpx 48rpx;
    width: calc(100% - 96rpx);
    padding-top: 12rpx;
    padding-bottom:calc(48rpx + env(safe-area-inset-bottom));
    background-color: white;
    bottom: 0;
    border-top: 2rpx solid #efefef;


    .replyInput{
        font-weight: 400;
        font-size: 24rpx;
        line-height: 48rpx;
        text-align: left;
        color: #999;
    }
    .reply{
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .reply-interaction{
        display: flex;
        align-items: center;

    }
}
.currentNum{
    font-weight: 400;
    font-size: 24rpx;
    text-align: center;
    color: #333;
}
.disabled-btn {
    border-color: #cccccc !important;
}
// 加载
.loading-text, .no-more-text {
    padding: 20rpx;
    text-align: center;
    color: #888;
    font-size: 24rpx;
}
.l20 {
    margin-left: 20px;
}

.r13 {
    margin-right: 13px;
}

.r8 {
    margin-right: 8px;
}
</style>

